Now we figure out how to trigger our function!
We need to attach an API Gateway which will allow us to call our lambda function from the internet.
Run:
- npm install --save @aws-cdk/aws-apigateway
Then import it to the stack file: import * as apiGateway from "@aws-cdk/aws-apigateway";
Now we will use apiGateway to create a REST API for our application.
Add the following before the closing of the TodoAppStack constructor:
new apiGateway.LambdaRestApi(this, "Endpoint", {handler: helloLambda});
Let's also update the body of our handler inside our lambda function to:
body: 'Hello, nothanii friends! You've hit ${event.path}\n'
Run cdk diff (a lot of changes will be displayed - this will be the code added by cdk due to adding apiGateway), then cdk deploy.
Once you've deployed successfully, the terminal will output a URL. Click on it to see your lambda function live on the internet.
You can also check your newly created resources in the aws console. If you click on your lambda function you'll also see that this function now has a trigger (API Gateway) associated with it.
Pass environment variables to a lambda function deployed with AWS CDK
Let's pass an environment variable to our lambda function.
We can do that by adding a prop to our helloLambda function in the stacks file:
const helloLambda = new lambda.Function(this, "HelloLambda", {environment: { isProduction: "absolutely not" }});
Let's console.log our variable:
console.log("isProduction?", process.env.isProduction);
Once you've deployed, you'll be able to see the log. Click on Test in the aws console and checkout the Environment variables.